import { ICommonParams } from '@feidao/service/interfaces';
import batch_push from '@feidao/web/atom/nodejs/msg/batch-push';
import ali_scan_pay from '@feidao/web/atom/nodejs/ali/scan-pay';
import { systemid } from './config';
import nodejs from '@feidao/web/atom/nodejs/msg/nodejs';
import log from '@feidao/web/atom/nodejs/logger/log';

export default async function atom(msg: ICommonParams, action_id: string, session_id: string, _spaceid: string) {

	const query = msg.query;
	const spaceid = query.spaceid;
	// 传入的参数中必须包含当前登录用户的sessionid，调用原子操作传入此sessionid
	const sessionid = query.sessionid;
	const doccode = query.doccode;

	let b = '';
	// 判断浏览器类型
	const user_agent = msg.headers['user-agent'];
	if (/MicroMessenger/.test(user_agent)) {
		b = 'weixin';
	} else if (/AlipayClient/.test(user_agent)) {
		b = 'alipay';
	} else {
		return { data: '请用微信或支付宝打开' };
	}

	// 对数据进行处理
	if (!doccode) {
		return { data: '缺少参数' };
	} else {
		// 微信公众号的appid
		const appid = 'wxf518687e6f97df6b';
		const business_key = doccode;

		// 推送消息，表明已经扫码
		// await batch_push(action_id, sessionid, spaceid, [
		// 	{
		// 		ToId: sessionid,
		// 		BusinessKey: business_key,
		// 		ControlParam: {
		// 			pay_type: b
		// 		}
		// 	}
		// ]);
		if (b === 'weixin') {
			// 微信浏览器，重定向到微信授权地址
			const url = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid=' + appid + '&redirect_uri=' + encodeURIComponent('http://www.daokes.com/test/wx-pay.html') + '&response_type=code&scope=snsapi_base&state=' + encodeURIComponent(JSON.stringify({ doccode, sessionid })) + '#wechat_redirect';
			log('url====================', url);
			return {
				cookie: { sessionid },
				redirect: url
			};
		} else if (b === 'alipay') {
			// 支付宝浏览器，获取订单信息，调用支付宝扫一扫支付
			// 获取商品基本信息

			// const data = await nodejs(action_id, session_id, spaceid, '', {});
			// if (data) {
			// const subject = data.commodity_name;
			// const amount = data.account_sum;
			// 调用扫码支付
			const body = {
				spaceid,
				sessionid
			};

			const scan_res = await ali_scan_pay(action_id, sessionid, spaceid, systemid, 'admin', business_key, doccode, 0.01, '测试支付', '30m', true, body, 200, 200);
			const url = scan_res.QRCode;
			log('----------ali pay url-----------', url);
			return {
				cookie: { sessionid },
				redirect: url
			};
		} else {

		}
		// }
	}
}
